/* Copyright (c) 2009 yinquan zhang
   See the file LICENSE.txt for licensing information. */

/*
Components.utils.import("resource://ballbet/Observers.js");
Components.utils.import("resource://ballbet/log4moz.js");
Components.utils.import("resource://ballbet/service.js");
*/

const Cc = Components.classes;
const Ci = Components.interfaces;

const nsITimer = Ci.nsITimer;
var domLeagues, domTeams;

var appInfo = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo);

/*
    定义全局的信息变量
*/
var macauLeagues = []; //联盟信息
var macauTransOrder = []; //让球信息
var macauSizeOrder = []; //大小盘信息
var macauLeagueLive = null; //主网正在进行比赛的联盟个数
var macauLive = null; //主网正在进行比赛的比赛个数，根据时间来判别
var lijiLeagues = [];
var lijiTransOrder = [];
var lijiSizeOrder = [];

var shabaLeagues = [];
var shabaTransOrder = [];
var shabaSizeOrder = [];

var newballLeagues = [];
var newballTransOrder = [];
var newballSizeOrder = [];

const sites = {macau: 'macau', liji: 'liji', shaba: 'shaba', newball: 'newball'};

//包括：0:盘口、1:水位差、2:当前副网的水位ID、3:水位的位置(0:1)、4.5:利记，6.7:沙巴，
//    8.9:新球的水位,10:主网水位ID,11:副网名称,12:副网水位,13:主网水位
//个数与macauLive一致
var curTransLevelInfos = [];

var curSizeLevelInfos = [];


var curSelInfos = [];
var awaySites = {name:"", levelid:""};

function $(id, doc) {
  if(doc) {
    return doc.getElementById(id);
  }
  return document.getElementById(id);
}

var loaded = false;
//show message
function jsdump(str) {
  Cc['@mozilla.org/consoleservice;1'].getService(Ci.nsIConsoleService).logStringMessage(str);
}

//show error
function jserror(str) {
  Components.utils.reportError(str);
}

/*
    get proference file folder
*/
function getProfDirFile() {
  var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
  return file;
}

/*
  player sound
*/
function playSound() {
  var soundURL = "chrome://ballbet/content/sounds/bet.wav";
  var player = Cc["@mozilla.org/sound;1"].createInstance(Ci.nsISound);
  var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
  var url = ioService.newURI(soundURL, null, null);
  player.play(url);
  
  //Cc["@mozilla.org/sound;1"].createInstance(Ci.nsISound).playSystemSound(sound);
  //Cc["@mozilla.org/sound;1"].createInstance(Ci.nsISound).beep();
}
/*
 load xml by the file name without path
 */
function loadXMLByName(name) {
  
  var file = getProfDirFile();
  
  file.append(name); // filename
  var fileName = "file:///" + file.path;
  if (!file.exists()) {
    //first run the app, use the default file
    var str = "chrome://ballbet/content/setting/";
    str = str.concat(name);
    
    fileName = str;
  }
  
  var req = new XMLHttpRequest();
  req.open("GET", fileName, false);
  req.send(null);
  return req.responseXML;
}

/*
    save xml by name and the xml dom 
*/
function saveXMLByName(name, dom) {
  var serializer = new XMLSerializer();
  var file = getProfDirFile();
  file.append(name); // filename
  var foStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
  foStream.init(file, 0x02 | 0x08 | 0x20, 0664, 0); // write, create, truncate
  serializer.serializeToStream(dom, foStream, ""); // rememeber, doc is the DOM tree
  foStream.close();
}

window.addEventListener("load", initialize, false);
window.addEventListener("unload", uninitialize, false);
window.setTimeout("loadSettings();", 4000);

function openMacauPopup() {
  var macauBrowser = $("macau-browser");

}

// Initializes the extension
function initialize(event) {
  try {
    //playSound();
//    jsdump("web sites loaded...");

    //澳门网
    var macauBrowser = $("macau-browser");
      
    var macau = getStringPreference("macau.home", false);
    macauBrowser.setAttribute("homepage", getStringPreference("macau.home", false));
    macauBrowser.addEventListener("load", macauPageLoad, true);
    macauBrowser.addEventListener("unload", pageUnload, true);
    

    var loginUrl = getStringPreference("macau.loginurl", false);
    macauBrowser.loadURI(loginUrl, null, null);

  
    //macauBrowser.goHome();
    //利记网
    var lijiBrowser = $("liji-browser");
    lijiBrowser.setAttribute("homepage", getStringPreference("liji.home", false));
    lijiBrowser.addEventListener("load", lijiPageLoad, true);
    lijiBrowser.addEventListener("unload", lijiPageUnload, true);

    lijiBrowser.goHome();

    //沙巴网
    var shabaBrowser = $("shaba-browser");
    shabaBrowser.setAttribute("homepage", getStringPreference("shaba.home", false));
    shabaBrowser.addEventListener("load", shabaPageLoad, true);
    shabaBrowser.addEventListener("unload", shabaPageUnload, true);
    shabaBrowser.goHome();

    //新球网
    var newballBrowser = $("newball-browser");
    newballBrowser.setAttribute("homepage", getStringPreference("newball.home", false));
    newballBrowser.addEventListener("load", newballPageLoad, true);
    newballBrowser.addEventListener("unload", newballPageUnload, true);

    newballBrowser.goHome();

    window.removeEventListener("load", initialize, false);

  } catch(e) {
//    jsdump("initialize:  " + e);
  }
}

function loadSettings() {
  //加载球队和联赛名字，保存在同名设置对话框关闭时
  var leagueNames = getStringPreference("setting.leaguenames", false);  //"联赛名称.xml"; //
  var teamNames = getStringPreference("setting.teamnames", false);
  domLeagues = loadXMLByName(leagueNames);
  domTeams = loadXMLByName(teamNames);
//  jsdump("加载球队和联赛名字: leagueNames:" + leagueNames + ";teamNames:" + teamNames);
  
}

// Uninitializes the extension
function uninitialize(event) {
  // Try to get the window content
  try {
    getContentWindow("macau-browser").removeEventListener("load", macauPageLoad, false);
    getContentWindow("macau-browser").removeEventListener("unload", pageUnload, true);

    window.removeEventListener("close", uninitialize, false);

  } catch(e) {
    // Do nothing
  }
}

function goHomeMacau() {
  $("macau-browser").goHome();
  var timer = Cc["@mozilla.org/timer;1"].createInstance(nsITimer);
  var interval = getIntegerPreference("macau.click.interval", false);
  //alert(interval);
  //timer.initWithCallback(goMacauSecondClick, interval, nsITimer.TYPE_ONE_SHOT);
}

function goMacauFirstClick() {
  var maindoc = $("macau-browser").contentDocument;
  var frame = getStringPreference("macau.click.first.frame", false);

  var doc = maindoc.getElementsByName(frame)[0].contentDocument;

  var id = getStringPreference("macau.click.first", false);

  var ele = doc.getElementById(id);

  var timer = Cc["@mozilla.org/timer;1"].createInstance(nsITimer);
  var interval = getIntegerPreference("macau.click.interval", false);

  timer.initWithCallback(goMacauSecondClick, interval, nsITimer.TYPE_ONE_SHOT);

}

function goMacauSecondClick() {
  var frame = getStringPreference("macau.click.sceond.frame", false);
  
  var maindoc = $("macau-browser").contentDocument;
  
  var doc = maindoc.getElementsByName(frame)[0].contentDocument;
  
  var id = getStringPreference("macau.click.second", false);
  var ele = doc.getElementById(id);
  
}

function loginMacau() {
  
  var doc = $("macau-browser").contentDocument;
  
  var prestring = getStringPreference("macau.login.form", false);
  
  var form = doc.getElementsByName(prestring)[0];

  prestring = getStringPreference("macau.login.username", false);

  var userName = doc.getElementsByName(prestring)[0];
  prestring = getStringPreference("macau.login.password", false);

  var password = doc.getElementsByName(prestring)[0];
  userName.value = getStringPreference("macau.username", false);
  password.value = getStringPreference("macau.password", false);
  form.submit();

  //delay and go Home
  var timer = Cc["@mozilla.org/timer;1"].createInstance(nsITimer);
  var interval = getIntegerPreference("macau.click.interval", false);
  timer.initWithCallback(goHomeMacau, interval, nsITimer.TYPE_ONE_SHOT);
  
}

function macauPageLoad(event) {
  if (loaded == true) return;
  loginMacau();
  loaded = true;
}

// Handles the page being loaded
function pageLoad(event) {
//  jsdump('pageLoad');

  var target = event.target;
//  jsdump(target.title);

  var str = target.title;
  str = str.toLowerCase();
  if (str.search(/login/) > -1) {
    loginMacau();
  }
}

// Handles the page being unloaded
function pageUnload(event) {

}

function transferOrderShow() {
//  jsdump("transferOrderShow");
  $("group_caption").label = "让球盘"; //getStringPreference("transorder", false);
  $("browser.transfer.order").hidden = false;
  $("browser.size.order").hidden = true;
}

function sizeOrderShow() {
//  jsdump("sizeOrderShow");
  $("group_caption").label = "大小盘"; // getStringPreference("sizeorder", false);
  $("browser.transfer.order").hidden = true;
  $("browser.size.order").hidden = false;
}

function clearOrderShow(browserID) {
  var doc = $(browserID).contentDocument;
  var table = doc.getElementById("table.infos");
  var rows = table.rows;
  var length = rows.length;
  if (length > 2) {
    var i = 0;
    for (var end = length - 1; end >= 2; end--) {
      table.deleteRow(end);
    }
  }
}

/*
    创建所有的数据行，并且设置好风格，然后再统一添加数据
*/
function createOrderTableRow(browserID) {
  var doc = $(browserID).contentDocument;
  var tbody = doc.getElementById("tbody.infos");
  var length = macauTransOrder.length;
  for (var i = 0; i < length; i++) {
    var row = doc.createElement("tr");
    row.setAttribute("align", "center");
    if (macauLive == null) macauLive = 0;
    if (i < macauLive) {
      row.setAttribute("class", "rowlive");
    } else {
      row.setAttribute("class", "rowback");
    }

    //序号
    var tdNum = doc.createElement("td");
    tdNum.setAttribute("id", "number");
    tdNum.appendChild(doc.createTextNode(""));
    row.appendChild(tdNum);

    //联赛
    var tdLeague = doc.createElement("td");
    tdLeague.setAttribute("id", 'league');
    tdLeague.appendChild(doc.createTextNode(""));
    row.appendChild(tdLeague);

    //球队
    var tdTeams = doc.createElement("td");
    tdTeams.setAttribute("id", 'teams');
    tdTeams.appendChild(doc.createTextNode(""));
    tdTeams.appendChild(doc.createElement("br"));
    tdTeams.appendChild(doc.createTextNode(""));
    row.appendChild(tdTeams);

    //时间
    var tdTime = doc.createElement("td");
    tdTime.setAttribute("id", 'time');
    tdTime.appendChild(doc.createTextNode(""));
    tdTime.appendChild(doc.createElement("br"));
    tdTime.appendChild(doc.createTextNode(""));
    row.appendChild(tdTime);

    //盘口
    var tdGate = doc.createElement("td");
    tdGate.setAttribute("id", 'gate');
    tdGate.appendChild(doc.createTextNode(""));
    row.appendChild(tdGate);

    //水位差
    var tdLevelSub = doc.createElement("td");
    tdLevelSub.setAttribute("id", 'subLevel');
    tdLevelSub.appendChild(doc.createTextNode(""));
    row.appendChild(tdLevelSub);

    //主网水位变化
    var tdLevelChange = doc.createElement("td");
    tdLevelChange.setAttribute("id", 'levelChange');
    tdLevelChange.appendChild(doc.createTextNode(""));
    row.appendChild(tdLevelChange);

    //澳门网水位
    var tdMacauLevel = doc.createElement("td");
    tdMacauLevel.setAttribute("id", 'macauLevel');
    tdMacauLevel.setAttribute("class", "level");
    tdMacauLevel.appendChild(doc.createTextNode(""));
    tdMacauLevel.appendChild(doc.createElement("br"));
    tdMacauLevel.appendChild(doc.createTextNode(""));
    row.appendChild(tdMacauLevel);

    //利记网水位
    var tdLijiLevel = doc.createElement("td");
    tdLijiLevel.setAttribute("id", 'lijiLevel');
    tdLijiLevel.setAttribute("class", "level");
    tdLijiLevel.appendChild(doc.createTextNode(""));
    tdLijiLevel.appendChild(doc.createElement("br"));
    tdLijiLevel.appendChild(doc.createTextNode(""));
    row.appendChild(tdLijiLevel);

    //沙巴网水位
    var tdShabaLevel = doc.createElement("td");
    tdShabaLevel.setAttribute("id", 'shabaLevel');
    tdShabaLevel.setAttribute("class", "level");
    tdShabaLevel.appendChild(doc.createTextNode(""));
    tdShabaLevel.appendChild(doc.createElement("br"));
    tdShabaLevel.appendChild(doc.createTextNode(""));
    row.appendChild(tdShabaLevel);

    //新球网水位
    var tdNewballLevel = doc.createElement("td");
    tdNewballLevel.setAttribute("id", 'newballLevel');
    tdNewballLevel.setAttribute("class", "level");
    tdNewballLevel.appendChild(doc.createTextNode(""));
    tdNewballLevel.appendChild(doc.createElement("br"));
    tdNewballLevel.appendChild(doc.createTextNode(""));
    row.appendChild(tdNewballLevel);

    //加入table中
    tbody.appendChild(row);
  }
}

/*
    清空list betinfo中的所有内容
*/
function RemoveListBetinfo() {
  var listbox = $("list-betinfos");
  var count = listbox.itemCount;
  for (var i = count - 1; i >= 0; i--) {
    listbox.removeItemAt(i);
  }
}

/*
    添加新的投注信息时，需要把原来的清除 

*/

function clearListBetInfo() {
  var listbox = $("list-betinfos");
  var count = listbox.itemCount;
  for (var i = count - 1; i >= 0; i--) {
    listbox.removeItemAt(i);
  }
}

/*
    添加新的投注
    0:投注类型,1:水位差,2:盘口，3：主队,4:客队
*/

function AddListBetinfo(type, levelSub, gate, mainTeam, assisTeam, index) {
  var listbox = $("list-betinfos");
  function addItem(item, value, collapsed) {
    var cell = document.createElement("listcell");
    cell.setAttribute("label", value);
    if (collapsed != undefined) {
      cell.setAttribute("collapsed", collapsed);
    }
    item.appendChild(cell);
  }

  var item = document.createElement("listitem");

  addItem(item, type);
  addItem(item, levelSub);
  addItem(item, gate);
  addItem(item, mainTeam);
  addItem(item, assisTeam);
  addItem(item, index, true);
  listbox.appendChild(item);
}

function setOrderShowInfo(browserID, arrOrder, curOrderInfos, type) {
  var doc = $(browserID).contentDocument;
  var tbody = doc.getElementById("tbody.infos");
  var rows = tbody.rows;
  if (rows.length <= 0) return;
  
  //0:序号，1：联赛，2：球队，3：时间，4：类型，5：水位差，6：比分
  //7：澳门网，8：利记网，9：沙巴网，10：新球网
  for (var i = 0; i < rows.length; i++) {
    var tds = rows[i].cells;
    tds[0].textContent = i;
    tds[1].textContent = arrOrder[i].leagueName;
    tds[2].childNodes[0].textContent = arrOrder[i].homeTeam;
    tds[2].childNodes[2].textContent = arrOrder[i].awayTeam;
    tds[3].childNodes[0].textContent = arrOrder[i].time1;
    tds[3].childNodes[2].textContent = arrOrder[i].time2;
    if (macauLive == null) macauLive = 0;
    //如果小于正在就行的比赛数目，就可以进行计算
    if (i < macauLive) {
      //tds[4] = arrOrder[i][5];
      var leftGates = arrOrder[i].homeGates;
      var rightGates = arrOrder[i].awayGates;
      //让球盘显示的是盘口
      tds[4].textContent = curOrderInfos[i].gate;
      tds[5].textContent = curOrderInfos[i].levelSub;
      if(curOrderInfos[i].levelSub <0)
        tds[5].textContent = '';
        
      tds[6].textContent = arrOrder[i].homeScore + " : " + arrOrder[i].awayScore;
      tds[7].childNodes[0].textContent = arrOrder[i].homeLevel;
      tds[7].childNodes[2].textContent = arrOrder[i].awayLevel;
      tds[8].childNodes[0].textContent = curOrderInfos[i].lijiHomeLevel;
      tds[8].childNodes[2].textContent = curOrderInfos[i].lijiAwayLevel;
      tds[9].childNodes[0].textContent = curOrderInfos[i].shabaHomeLevel;
      tds[9].childNodes[2].textContent = curOrderInfos[i].shabaAwayLevel;
      tds[10].childNodes[0].textContent = curOrderInfos[i].newballHomeLevel;
      tds[10].childNodes[2].textContent = curOrderInfos[i].newballAwayLevel;
      var temp = "index: "+ i+"; 投注类型："+type+"; 水位差："+subLevel+"; 盘口："+curOrderInfos[i].gate+
      "; 主队："+arrOrder[i].homeTeam+"; 客队："+arrOrder[i].awayTeam;

      //jsdump("setOrderShowInfo: "+type);
      //jsdump("homeWebLevelID: "+curOrderInfos[i].homeWebLevelID+"; awayWebLevelID: "+curOrderInfos[i].awayWebLevelID);
      
      //如果水位差大于0.00，那么就可以进行投注
      var subLevel = curOrderInfos[i].levelSub;
      if (subLevel && subLevel >= 0.0) {
        AddListBetinfo(type, subLevel, curOrderInfos[i].gate, arrOrder[i].homeTeam, arrOrder[i].awayTeam, i);
        playSound();
      }
    }

  }

}

/*
    点击投注信息，更新相关的信息显示
*/
function betInfoListClicked(event) {
  awaySites = {name:"", levelid:""};
  curSelInfos = [];
  
  var target = event.target;
  //如果选中了item，就显示当前选中的，否则清楚原来选择的    
  if (target.tagName == "listitem") {
    var selItem = target;
    var cells = selItem.childNodes;
    var type = cells[0].getAttribute("label");
    var index = cells[5].getAttribute("label");
    var info = [];
    for (var i = 0; i < 20; i++) info[i] = '';
    /*= [0:betType, 1:betGate, 2:league, 3:mainTeam, 4:assistTeam, 5:timeDay,
         6:time, 7:mainLevel,8:macauM, 9:macauA, 10:lijiM, 11:lijiA, 12:shabaM,
         13:shabaA, 14:newballM, 15:newballA, 16:assistLevel, 17:levelSub]
                  */
    function constructInfo(info, macauInfo, curInfo) {
      try {
        info[1] = curInfo.gate;
        info[2] = macauInfo.leagueName;
        info[3] = macauInfo.homeTeam;
        info[4] = macauInfo.awayTeam;
        info[5] = macauInfo.time1;
        info[6] = macauInfo.time2;
        info[7] = curInfo.homeWebLevel;
        info[8] = macauInfo.homeLevel;
        info[9] = macauInfo.awayLevel;
        info[10] = curInfo.lijiHomeLevel;
        info[11] = curInfo.lijiAwayLevel;
        info[12] = curInfo.shabaHomeLevel;
        info[13] = curInfo.shabaAwayLevel;
        info[14] = curInfo.newballHomeLevel;
        info[15] = curInfo.newballAwayLevel;
        info[16] = curInfo.awayWebLevel;
        info[17] = curInfo.levelSub;
      } catch(ex) {
//        jsdump("constructInfo: " + ex);
      }
    }

    var macauInfo;
    var curInfo;
    if (type == '让球盘') {
      info[0] = "让球盘";
      macauInfo = macauTransOrder[index];
      curInfo = curTransLevelInfos[index];

      //水位
    } else if (type == '大小盘') {
      info[0] = '大小盘';
      macauInfo = macauSizeOrder[index];
      curInfo = curSizeLevelInfos[index];
    }
    constructInfo(info, macauInfo, curInfo);
    setSelectinfoBrowser(info);

    curSelInfos = info;
    curSelInfos.push(sites.macau); //index = 18主网
    curSelInfos.push(curInfo.homeWebLevelID); //index = 19主网LevelID
    curSelInfos.push(curInfo.awayWebName); //index = 20 副网
    curSelInfos.push(curInfo.awayWebLevelID); //index = 21 副网LevelID
    
    awaySites.name = curInfo.awayWebName;
    awaySites.levelid = curInfo.awayWebLevelID;
    //找到对应的然后显示出来，并为自动投注做好准备
    //这里需要主网的LevelID，副网的网站和LevelID
    //主网
    //jsdump("sites.macau:"+sites.macau+"; homeWebLevelID: "+curInfo.homeWebLevelID);
    clickBetLevel(sites.macau, curInfo.homeWebLevelID);
    //副网
    //jsdump("awayWebName: "+curInfo.awayWebName+"; awayWebLevelID："+curInfo.awayWebLevelID)
    clickBetLevel(curInfo.awayWebName, curInfo.awayWebLevelID);

    $("des_mainTeam").setAttribute("value", '澳门网');
    var assis = '利记网';
    if(sites.shaba == curInfo.awayWebName) assis = '沙巴网';
    if(sites.newball == curInfo.awayWebName) assis = '新球网';
    $("des_assistTeam").setAttribute("value", assis);
    $("des_mainLevel").setAttribute("value", curInfo.homeWebLevel);
    $("des_assistLevel").setAttribute("value", curInfo.awayWebLevel);
    $("des_levelSub").setAttribute("value", curInfo.levelSub);

  } else {
    target.clearSelection();
    //清空单项显示
    setSelectinfoBrowser([]);
    //清空显示信息
    $("des_mainTeam").setAttribute("value", "");
    $("des_assistTeam").setAttribute("value", "");
    $("des_mainLevel").setAttribute("value", "");
    $("des_assistLevel").setAttribute("value", "");
    $("des_levelSub").setAttribute("value", "");

  }
}
//            联赛信息                             澳门网  	        利记网  	    沙巴网  	    新球网  	KK197网
//投注类型  盘口 联赛  主队/客队  时间  水位    水位（主/客）  	水位（主/客）  	水位（主/客）  	水位（主/客）  	水位（主/客）
// 20个参数
// var ifno = {betType, betGate, league, mainTeam, assistTeam, timeDay, time, mainLevel,
//    macauM, macauA, lijiM, lijiA, shabaM, shabaA, newballM, newballA, kk197M, kk197A, assistLevel, levelSub};
//  var info = ["亚洲盘", "2-2.5", "英超联赛", "曼哈顿", "牙买加", "上半场", "45:36", "1.8", "2.0", "1.5", "1.8", "1.5", "1.89", "1.26", "1.45", "1.56", "0.68", "-0.45", "0.76", "0.024"];
function setSelectinfoBrowser(info) {
  //表示清空显示
  if (info.length == 0) {
    for (var i = 0; i < 21; i++) {
      info[i] = "";
    }
  }
  var doc = $("selectinfo-browser").contentDocument;
  var rowElem = doc.getElementById('tr.data');
  rowElem.cells[0].textContent = info[0];
  rowElem.cells[1].textContent = info[1];
  rowElem.cells[2].textContent = info[2];
  rowElem.cells[3].childNodes[0].textContent = info[3];
  rowElem.cells[3].childNodes[2].textContent = info[4];
  rowElem.cells[4].childNodes[0].textContent = info[5];
  rowElem.cells[4].childNodes[2].textContent = info[6];
  rowElem.cells[5].textContent = info[7];
  rowElem.cells[6].childNodes[0].textContent = info[8];
  rowElem.cells[6].childNodes[2].textContent = info[9];
  rowElem.cells[7].childNodes[0].textContent = info[10];
  rowElem.cells[7].childNodes[2].textContent = info[11];
  rowElem.cells[8].childNodes[0].textContent = info[12];
  rowElem.cells[8].childNodes[2].textContent = info[13];
  rowElem.cells[9].childNodes[0].textContent = info[14];
  rowElem.cells[9].childNodes[2].textContent = info[15];
  rowElem.cells[10].textContent = info[16];
  rowElem.cells[11].textContent = info[17];
}
/*
    主网投注
*/

function mainBetClicked() {
  var number = $("text_mainBetLevel").value;
  number *= 1;
  //jsdump("mainBetClicked: " + number);
  autoBetValue(sites.macau, number);
}

/*
    副网投注
*/

function assistBetClicked() {
  var number = $("text_assistBetLevel").value;
  number *= 1;
//  jsdump("assistBetClicked: " + number);
  jserror(curSelInfos[20]);
  autoBetValue(awaySites.name, number);
}


//get macau dataxmlhttprequest
function getMacauHttprequest() {  
  var httpRequest = new XMLHttpRequest();
  if (httpRequest.overrideMimeType) {
    httpRequest.overrideMimeType('text/xml');
  }
  
  var currentTime = new Date()
//  jsdump("smacau tart time: "+currentTime.getTime());
  httpRequest.open('GET', 'https://www.macau-slot.com.mo/cust?action=go_dd&bet_in_run=1&class_sort=FB', true);  
  httpRequest.onreadystatechange = function (aEvt) {  
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {      
      var endTime = new Date()
      //jsdump(httpRequest.responseText);
      var xmldoc = httpRequest.responseXML;
      //var root_node = xmldoc.getElementsByTagName('root').item(0);
      //alert(root_node.firstChild.data);
      var ser = new XMLSerializer();
      var str = ser.serializeToString(xmldoc);
      jsdump(str);

      /*var range = doc.createRange();
      range.selectNode(doc.documentElement);
      var fragment = range.createContextualFragment(httpRequest.responseText);
      //doc.replaceChild(fragment, doc.documentElement);
      jsdump(fragment.innterHTML);*/

      jsdump("smacau ends time: "+ endTime.getTime());
      jsdump("smacau time elaspe: " + (endTime.getTime()-currentTime.getTime()));
    }
  };  
  httpRequest.send(null);  
}

//get liji data xmlhttprequest
function getLijiHttprequest() {
  var httpRequest = new XMLHttpRequest();
  if (httpRequest.overrideMimeType) {
    httpRequest.overrideMimeType('text/xml');
  }
  
  var currentTime = new Date()
  jsdump("liji start time: "+currentTime.getTime());
  
  httpRequest.onreadystatechange = function (aEvt) {  
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {      
      var endTime = new Date()
      var xmldoc = httpRequest.responseXML;
      //var root_node = xmldoc.getElementsByTagName('root').item(0);
      //alert(root_node.firstChild.data);
      var ser = new XMLSerializer();
      var str = ser.serializeToString(xmldoc);
      jsdump(str);
      //jsdump(httpRequest.responseText);
      jsdump("liji ends time: "+ endTime.getTime());
      jsdump("liji time elaspe: " + (endTime.getTime()-currentTime.getTime()));
    }
  };  
  
  httpRequest.open('POST', "http://9uho09878t.5166.info:8087/webroot/restricted/oddsdisplay/liveDataFrame.aspx", true);
  
  httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  httpRequest.setRequestHeader("Referer", "http://9uho09878t.5166.info:8087/webroot/restricted/oddsdisplay/live.aspx?sportid=1");
  httpRequest.setRequestHeader("Accept", "text/html, application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  
  var data = "synid=17382&sportid=1&oddsStyle=";
  httpRequest.send(data);
}


function makeRequest(url, data) {
  //data=   name=value&anothername=othervalue&so=on
  var httpRequest = new XMLHttpRequest();
  if (httpRequest.overrideMimeType) {
    httpRequest.overrideMimeType('text/xml');
  }

  if (!httpRequest) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
  }
  httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  httpRequest.addEventListener("progress", updateProgress, false);
  httpRequest.addEventListener("load",
  function(httpRequest) {
    transferComplete(event, httpRequest);
  },
  false);
  httpRequest.addEventListener("error", transferFailed, false);
  httpRequest.addEventListener("abort", transferCanceled, false);
  httpRequest.onreadystatechange = function() {
    alertContents(httpRequest);
  };
  httpRequest.open('POST', url, true);
  httpRequest.send(data);
  return true;
}

// progress on transfers from the server to the client (downloads)
function updateProgress(evt) {
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
  } else {
    // Unable to compute progress information since the total size is unknown
  }
}

function transferComplete(event, httpRequest) {
  alert("The transfer is complete.");
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      alert(httpRequest.responseText);
      var xmldoc = httpRequest.responseXML;
      var root_node = xmldoc.getElementsByTagName('root').item(0);
      alert(root_node.firstChild.data);

    } else {
      alert('There was a problem with the request.');
    }
  }
}

function transferFailed(evt) {
  alert("An error occurred while transferring the file.");
}

function transferCanceled(evt) {
  alert("The transfer has been canceled by the user.");
}

function alertContents(httpRequest) {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      alert(httpRequest.responseText);
      var xmldoc = httpRequest.responseXML;
      var root_node = xmldoc.getElementsByTagName('root').item(0);
      alert(root_node.firstChild.data);

    } else {
      alert('There was a problem with the request.');
    }
  }
}

/*
    澳门网刷新数据
*/
function refreshMacauData() {
//  jsdump("refreshMacauData: started");
  var maindoc = $("macau-browser").contentDocument;
  try {
    var frameName = getStringPreference("macau.data.frame", false);
    var mainFrame = maindoc.getElementsByName("mainFrame")[0].contentDocument;
    var frame = mainFrame.getElementsByName(frameName);
    var doc = frame[0].contentDocument;
    doc.location.reload();

  } catch(ex) {
    //jsdump("refreshMacauData: " + ex);
  }
  //jsdump("refreshMacauData: ended");
}

function refreshLijiData() {
//  jsdump("refreshLijiData: started");
  var maindoc = $("liji-browser").contentDocument;
  try {
    var doc = maindoc.getElementById("mainFrame").contentDocument;
    var btnRefresh = doc.getElementById("trefresh");
    //jsdump(btnRefresh);
    emulateClick(doc, btnRefresh);

  } catch(ex) {
    //jsdump("refreshLijiData: " + ex);
  }
  //jsdump("refreshLijiData: ended");

}

function refreshShabaData() {
//  jsdump("refreshShabaData: started");
  var maindoc = $("shaba-browser").contentDocument;
  try {
    var doc = maindoc.getElementById("mainFrame").contentDocument;
    //doc.location.reload();
    var btns = doc.getElementsByName('btnRefresh');
    for (var i = 0; i < btns.length; i++) {
      if (btns[i].getAttribute('target') == "_self") {
        //jsdump("emulateClick: " + btns[i]);
        emulateClick(doc, btns[i]);
        break;
      }
    }

  } catch(ex) {
    //jsdump("refreshShabaData: " + ex);
  }
  //jsdump("refreshShabaData: ended");
}

function refreshNewballData() {
//  jsdump("refreshNewballData: started");
  var maindoc = $("newball-browser").contentDocument;
  try {
    var doc = maindoc.getElementById("fraOdds").contentDocument;
    var btns = doc.getElementsByTagName('tbody');
    for (var i = 0; i < btns.length; i++) {
      if (btns[i].getAttribute('onclick') == "getOddsRB();") {
 //       jsdump("emulateClick: " + btns[i]);
        emulateClick(doc, btns[i]);
        break;
      }
    }

  } catch(ex) {
//    jsdump("refreshNewballData: " + ex);
  }
//  jsdump("refreshNewballData: ended");
}

// ****************************************************************************
// DOM Modification
function setOuterHTML(element, html)
{
  var doc = element.ownerDocument;
  var range = doc.createRange();
  range.selectNode(element || doc.documentElement);

  var fragment = range.createContextualFragment(html);
  var first = fragment.firstChild;
  var last = fragment.lastChild;
  element.parentNode.replaceChild(fragment, element);
  return [first, last];
}

function appendInnerHTML(element, html)
{
  var doc = element.ownerDocument;
  var range = doc.createRange();
  range.selectNode(doc.body);

  var fragment = range.createContextualFragment(html);
  element.appendChild(fragment);
}

function insertTextIntoElement(element, text)
{
  var command = "cmd_insertText";
  var controller = element.controllers.getControllerForCommand(command);
  if (!controller || !controller.isCommandEnabled(command))
      return;

  var params = Cc["@mozilla.org/embedcomp/command-params;1"].getService(Ci.nsICommandParams);
  params.setStringValue("state_data", text);

  //controller = this.QI(controller, Ci.nsICommandController);
  controller = controller.QueryInterface(Ci.nsICommandController);
  controller.doCommandWithParams(command, params);
}
